package com.igeek.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author fengqq
 * @Description 数据源相关的配置类
 * @Date 2024/8/20  11:41
 *
 * 切换druid数据源的步骤--自定义方式：
 *  1.引入druid依赖
 *  2.DataSourceAutoConfiguration --> @Configuration+ @Bean 替换底层的DataSource(默认使用的数据源HikariDataSource)
 *  3.@ConfigurationProperties 指定能够操作yml文件的前缀 实现配置绑定
 */
//@Configuration
public class DataSourceConfig {

    //@Bean 替换 底层的DataSource 不再让 Spring Boot 自动创建
//    @Bean
    //将全局配置文件中前缀为spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //开启SQL监控 SQl日志监控 SQL防火墙监控
        druidDataSource.setFilters("stat,slf4j,wall");
        return druidDataSource;
    }

    //通过RegistrationBean方式 注入StatViewServlet原生组件，开启监控页面
    //StatViewServlet 匹配的访问路径 /druid/*
//    @Bean
    public ServletRegistrationBean<StatViewServlet> servletServletRegistrationBean(){
        ServletRegistrationBean<StatViewServlet> registrationBean
                = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        //设置初始化参数 登陆页面的登录的用户名root 密码root resetEnable 重置功能是否禁用
        registrationBean.addInitParameter("loginUsername","root");
        registrationBean.addInitParameter("loginPassword","root");
        registrationBean.addInitParameter("resetEnable","false");
        return registrationBean;
    }

    //通过RegistrationBean方式 注入WebStatFilter原生组件，开启web监控
//    @Bean
    public FilterRegistrationBean<WebStatFilter> filterFilterRegistrationBean(){
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        WebStatFilter webStatFilter = new WebStatFilter();
        registrationBean.setFilter(webStatFilter);
        //设置初始化参数 排除路径
        registrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        //设置拦截路径
        registrationBean.setUrlPatterns(Stream.of("/*").collect(Collectors.toList()));
        return registrationBean;
    }
}
